﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TCP_Server
{
    public partial class Form1 : Form
    {
        SynchronizationContext sync1 = null;

        public Form1()
        {
            InitializeComponent();

            sync1 = SynchronizationContext.Current;

            textBox_IP.Text = "10.129.48.63";
            textBox_端口.Text = "12544";
        }

        Thread th1 = null; // 等待连接
        Thread th2 = null; // 接收数据

        void startThread() // 线程启动函数
        {
            th1 = new Thread(Waiting_for_connection) ;
            th1.Start();
        }

        void Waiting_for_connection() // 等待连接
        {
            while (true)
            {
                Thread.Sleep(100);
                if (button_打开.Text == "关闭")
                {
                    try
                    {
                        Socket_TCP_Server.Client_so = Socket_TCP_Server.Server_so.Accept(); // 服务器关闭时会抛出异常
                    }
                    catch (Exception)
                    {
                        Console.WriteLine("服务器已关闭");
                        break;
                    }

                    sync1.Post(Client_updata, Socket_TCP_Server.Client_so); // 更新 textBox comboBox 内容

                    Socket_TCP_Server.Server_send(Socket_TCP_Server.Client_so, "hello");
                    //start_ReceiveThread(); // 启动接收函数
                    start_ReceiveThread_new(Socket_TCP_Server.Client_so);
                }
            }
        }

        void Client_updata(object obj)// 更新 textBox comboBox 内容
        {
            Socket so = (Socket)obj;
            Socket_TCP_Server.judge_puls(
                        so.RemoteEndPoint.ToString(),
                        out Socket_TCP_Server.Client_IP,
                        out Socket_TCP_Server.Client_Port); // 解析 ip 与 端口
            string ip_port = Socket_TCP_Server.Client_IP + ":" + Socket_TCP_Server.Client_Port;
            Socket_TCP_Server.mySocketDict.Add(ip_port, so);
            comboBox_客户端列表.Items.Add(ip_port);
            comboBox_客户端列表.Text = ip_port;
        }

        void start_ReceiveThread_new(Socket So) // 启动接收函数
        {
            th2 = new Thread(ReceiveTaskMult);
            th2.Start(So);
        }

        void ReceiveTaskMult(object obj) // 接收函数
        {
            Socket So = (Socket)obj;
            Socket_TCP_Server.judge_puls(
                        So.RemoteEndPoint.ToString(),
                        out Socket_TCP_Server.Client_IP,
                        out Socket_TCP_Server.Client_Port); // 解析 ip 与 端口

            string ip_port = Socket_TCP_Server.Client_IP + ":" + Socket_TCP_Server.Client_Port;

            while (true)
            {
                Thread.Sleep(100);
                if (Socket_TCP_Server.mySocketDict.ContainsKey(ip_port))
                {
                    string str = Socket_TCP_Server.Receive(So);

                    if (str == false.ToString())
                    {
                        sync1.Post(dictDel_th, So);
                        break;
                    }
                    Socket_TCP_Server.judge_puls(
                        So.RemoteEndPoint.ToString(),
                        out Socket_TCP_Server.Client_IP,
                        out Socket_TCP_Server.Client_Port); // 解析 ip 与 端口
                    sync1.Post(update, str);
                }
                else
                    break;
            }
        }

        void update(object obj) // 将数据更新到页面
        {
            string ip_port = Socket_TCP_Server.Client_IP + ":" + Socket_TCP_Server.Client_Port;

            richTextBox_接收区.SelectionColor = Color.Black; // 改变插入颜色
            richTextBox_接收区.AppendText(DateTime.Now.ToString() + " [" + ip_port + "]" + "\r\n");  // 显示时间
            richTextBox_接收区.SelectionColor = Color.Green;  // 改变插入颜色
                                                           //richTextBox_接收区.AppendText(recvStr + "\r\n");  //显示接收的数据
            richTextBox_接收区.AppendText((string)obj + "\r\n");  //显示接收的数据

            // 让文本显示一直在最下方
            this.richTextBox_接收区.SelectionStart = this.richTextBox_接收区.Text.Length;
            this.richTextBox_接收区.ScrollToCaret();
        }

        void dictDel_th(object obj)
        {
            Socket soc = (Socket)obj;
            string ip_port = Socket_TCP_Server.Client_IP + ":" + Socket_TCP_Server.Client_Port;
            if (soc.Connected)
                dicDel(soc, ip_port);
        }

        void dicDel(Socket soc, string str)
        {
            Socket_TCP_Server.mySocketDict.Remove(str);
            comboBox_客户端列表.Items.Remove(str);

            if (comboBox_客户端列表.Text == str)
                comboBox_客户端列表.Text = "";

            soc.Close(10);
        }

        private void button_打开_Click(object sender, EventArgs e)
        {
            if (textBox_IP.Text != "" && textBox_端口.Text != "" && button_打开.Text == "打开")
            {
                Socket_TCP_Server.Server_IP = textBox_IP.Text;
                Socket_TCP_Server.Serrver_Port = textBox_端口.Text;
                Socket_TCP_Server.server_start();
                startThread(); // 启动等待连接函数

                label_状态.Text = "已开启";
                button_打开.Text = "关闭";
            }
            else if (button_打开.Text == "关闭")
            {
                Socket_TCP_Server.server_close();

                label_状态.Text = "未开启";
                button_打开.Text = "打开";
            }
        }

        private void button_退出_Click(object sender, EventArgs e)
        {
            Socket_TCP_Server.server_close();
            System.Environment.Exit(0);
        }

        private void button_踢出_Click(object sender, EventArgs e)
        {
            if (comboBox_客户端列表.Text != "" && Socket_TCP_Server.mySocketDict.ContainsKey(Socket_TCP_Server.Client_IP + ":" + Socket_TCP_Server.Client_Port))
            {
                dicDel(Socket_TCP_Server.mySocketDict[comboBox_客户端列表.Text], comboBox_客户端列表.Text);
            }

            
        }

        private void comboBox_客户端列表_TextUpdate(object sender, EventArgs e)
        {
            comboBox_客户端列表.Text = "";
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void richTextBox_接收区_TextChanged(object sender, EventArgs e)
        {

        }

        private void button_发送_Click(object sender, EventArgs e)
        {
            if (!(checkBox_群发.Checked) && comboBox_客户端列表.Text != "" && richTextBox_发送区.Text != "" && Socket_TCP_Server.mySocketDict.ContainsKey(comboBox_客户端列表.Text))
            {
                Socket_TCP_Server.Server_send(Socket_TCP_Server.mySocketDict[comboBox_客户端列表.Text], richTextBox_发送区.Text);
            }

            else if (checkBox_群发.Checked && richTextBox_发送区.Text != "")
            {
                for (int i = 0; i < comboBox_客户端列表.Items.Count; i++)
                {
                    Socket_TCP_Server.Server_send(Socket_TCP_Server.mySocketDict[comboBox_客户端列表.Items[i].ToString()], richTextBox_发送区.Text);
                }
            }
        }

        private void checkBox_群发_CheckedChanged(object sender, EventArgs e)
        {
            
        }
    }
}
